<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['project:group:add']"
          >创建工作区</el-button
        >
      </el-col>
    </el-row>

    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item>
        <el-input
          v-model="queryParams.siteGroupName"
          placeholder="工作区名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.groupId"
          placeholder="请选择企业"
          clearable
        >
          <el-option
            v-for="dict in dict.type.ly_group"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.projectId"
          placeholder="请选择项目"
          clearable
        >
          <el-option
            v-for="item in queryProjectList"
            :label="item.projectName"
            :value="item.id"
            :key="item.id"
          >
            {{ item.projectName }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.banId"
          placeholder="请选择楼栋"
          clearable
        >
          <el-option
            v-for="item in queryBanList"
            :label="item.banName"
            :value="item.banId"
            :key="item.banId"
          >
            {{ item.banName }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="queryParams.siteGroupType"
          placeholder="请选择类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.site_group_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.floorNumber"
          placeholder="所属楼层"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="workspaceList">
      <el-table-column type="index" label="序号" align="center" />
      <el-table-column label="工作区名称" align="center" prop="siteGroupName" />
      <el-table-column label="类型" align="center" prop="siteGroupType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.site_group_type"
            :value="scope.row.siteGroupType"
          />
        </template>
      </el-table-column>
      <el-table-column label="所属企业" align="center" prop="groupId">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ly_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="所属楼栋" align="center" prop="banName" />
      <el-table-column label="所属楼层" align="center" prop="floorNumber" />
      <el-table-column label="工位数" align="center" prop="siteNum" />
      <el-table-column label="面积(㎡)" align="center" prop="siteGroupArea" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateOrDetail(scope.row, '修改工作区')"
            v-hasPermi="['project:group:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdateOrDetail(scope.row, '工作区详情')"
            v-hasPermi="['project:project:detail']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['project:group:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工位区对话框 -->
    <el-dialog
      :fullscreen="true"
      :center="true"
      :title="title"
      :visible.sync="open"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <div class="dialog-content">
          <el-form-item label="工作区名称：" prop="siteGroupName">
            <el-input
              v-model="form.siteGroupName"
              style="width: 217px"
              placeholder="请输入工作区名称"
              :readonly="title === '工作区详情'"
            />
          </el-form-item>
          <el-form-item label="所属项目：" prop="projectId">
            <div class="project_content">
              <el-input
                placeholder="点击查询"
                :readonly="true"
                v-model="form.projectName"
              ></el-input>
              <el-button
                type="text"
                class="project-select-button"
                @click="projectSelect"
                v-if="title !== '工作区详情'"
                >查询</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="所属楼栋：" prop="banId">
            <el-select
              placeholder="请选择楼栋"
              v-model="form.banId"
              @change="handleBanChange"
              :disabled="title === '工作区详情'"
            >
              <el-option
                v-for="ban in banList"
                :label="ban.banName"
                :value="ban.banId"
                >{{ ban.banName }}</el-option
              >
            </el-select>
          </el-form-item>
          <el-form-item label="所属楼层：" prop="floorNumber">
            <el-select
              placeholder="请选择楼层"
              v-model="form.floorNumber"
              :disabled="title === '工作区详情'"
            >
              <el-option
                v-for="item in floorList"
                :label="item.floorNumber"
                :value="item.floorNumber"
                >{{ item.floorNumber }}
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工作区类型：" prop="siteGroupType">
            <el-select
              v-model="form.siteGroupType"
              placeholder="请选择类型"
              :disabled="title === '工作区详情'"
            >
              <el-option
                v-for="dict in dict.type.site_group_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="工作区面积：" prop="siteGroupArea">
            <el-input
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              v-model.number="form.siteGroupArea"
              placeholder="请输入工作区面积"
              style="width: 217px"
              :readonly="title === '工作区详情'"
            >
              <template #append>m²</template>
            </el-input>
          </el-form-item>
          <el-form-item label="工作区介绍：" prop="siteGroupRemark">
            <el-input
              v-model="form.siteGroupRemark"
              placeholder="备注描述..."
              style="width: 50%"
              :readonly="title === '工作区详情'"
            />
          </el-form-item>
          <el-form-item label="工位：" prop="siteGroupRemark">
            <div class="station-content">
              <div
                class="station-item"
                v-for="index in siteNameList.length"
                :key="index"
              >
                <el-input
                  placeholder="请输入工位名称"
                  v-model="siteNameList[index - 1]"
                  :readonly="title === '工作区详情'"
                >
                </el-input>
                <svg-icon
                  icon-class="close"
                  class-name="close-class"
                  @click="deleteStation(index - 1)"
                  v-if="title !== '工作区详情'"
                />
              </div>
              <el-button
                type="text"
                @click="addStation"
                v-if="title !== '工作区详情'"
              >
                <el-icon class="el-icon-plus"></el-icon>
                添加工位
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="工作区图片：">
            <el-upload
              multiple
              :file-list="fileList"
              list-type="picture-card"
              :action="uploadUrl"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              :class="{ disabled: title === '工作区详情' }"
            >
              <el-icon class="el-icon-plus"></el-icon>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          v-if="title !== '工作区详情'"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog title="项目查询器" width="60%" :visible.sync="openProjectSelect">
      <ProjectManagement ref="projectRef" :is-component="true" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelProjectSelect">取 消</el-button>
        <el-button type="primary" @click="confirmProjectSelect"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSiteGroup,
  getSiteGroup,
  delSiteGroup,
  addSiteGroup,
  updateSiteGroup,
  getBanByProjectId,
  getFloorsByProjectIdAndSiteGroupId,
  getAllProjectsApi,
  getAllBansApi,
} from "@/api/space/workSpace";
import ProjectManagement from "@/views/project/projectManagement/index.vue";

export default {
  name: "workspace",
  // 数据字典
  dicts: ["ly_group", "site_group_type"],
  components: { ProjectManagement },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作区表格数据
      workspaceList: [],
      // 工位列表
      siteNameList: [],
      // 楼栋列表
      banList: [],
      // 楼层列表
      floorList: [],
      // 用于查询的所有项目列表
      queryProjectList: [],
      // 用于查询的所有楼栋列表
      queryBanList: [],
      // 文件上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + "/ly/fileUpload",
      // 图片上传列表
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 项目选择器弹出层
      openProjectSelect: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        projectId: null,
        banId: null,
        siteGroupType: null,
        floorNumber: null,
        siteGroupName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        banId: [{ required: true, message: "请选择楼栋", trigger: "blur" }],
        siteGroupName: [
          { required: true, message: "请输入楼宇名称", trigger: "blur" },
        ],
        siteGroupType: [
          { required: true, message: "请选择工位类型", trigger: "change" },
        ],
        siteNum: [{ required: true, message: "请输入工位数", trigger: "blur" }],
        siteGroupArea: [
          { required: true, message: "请输入工位区面积", trigger: "blur" },
        ],
        floorNumber: [
          {
            required: true,
            message: "请输入楼层号",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    // 查询所有项目列表
    this.getAllProjects();
    // 查询所有楼栋列表
    this.getAllBans();
  },
  methods: {
    /** 查询工作区列表 */
    getList() {
      this.loading = true;
      listSiteGroup(this.queryParams).then((response) => {
        this.workspaceList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        siteGroupId: null,
        siteGroupName: null,
        projectId: null,
        siteGroupType: null,
        banId: null,
        floorNumber: null,
        siteGroupArea: null,
        siteGroupRemark: null,
        siteNameList: [],
        imgs: [],
      };
      this.siteNameList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        groupId: null,
        projectId: null,
        banId: null,
        siteGroupType: null,
        floorNumber: null,
        siteGroupName: null,
      };
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建工作区";
    },
    /** 修改/详情按钮操作 */
    handleUpdateOrDetail(row, title) {
      this.reset();
      // 获取工作区详情
      getSiteGroup(row.siteGroupId).then((response) => {
        this.form = response.data;
        // 后端接口没有返回项目名称
        this.form.projectName = row.projectName;
        this.siteNameList = response.data.siteNameList;
        this.form.imgs = this.fileList = JSON.parse(response.data.imgs);
        // 获取对应楼栋和楼层
        this.getBanList(this.form.projectId);
        this.getFloorList(this.form.projectId, this.form.banId);

        this.title = title;
        this.open = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.siteNameList = this.siteNameList;
          this.form.imgs = JSON.stringify(this.form.imgs);

          if (this.form.siteGroupId != null) {
            updateSiteGroup(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSiteGroup(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const siteGroupId = row.siteGroupId;
      const siteGroupName = row.siteGroupName;
      this.$modal
        .confirm('确认删除"' + siteGroupName + '"吗？')
        .then(function () {
          return delSiteGroup(siteGroupId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 查询项目信息 */
    projectSelect() {
      this.openProjectSelect = true;
    },
    /** 取消查询项目信息 */
    cancelProjectSelect() {
      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 获取楼栋列表 */
    getBanList(projectId) {
      getBanByProjectId(projectId).then((res) => {
        this.banList = res.code === 200 ? res.data : [];
      });
    },
    /** 获取楼层列表 */
    getFloorList(projectId, banId) {
      getFloorsByProjectIdAndSiteGroupId(projectId, banId).then((res) => {
        this.floorList = res.code === 200 ? res.data : [];
      });
    },
    /** 确认选择项目 */
    confirmProjectSelect() {
      const currentProject = this.$refs.projectRef.getCurrentProject();
      this.form.projectName = currentProject.projectName;
      this.form.projectId = currentProject.id;
      // 获取该项目的所有楼栋信息
      this.getBanList(this.form.projectId);
      // 清空楼栋和楼层的初始值
      this.form.banId = null;
      this.form.floorNumber = null;
      this.floorList = [];

      this.openProjectSelect = false;
      this.$refs.projectRef.reset();
    },
    /** 添加工位 */
    addStation() {
      this.siteNameList.push("");
    },
    /** 删除工位 */
    deleteStation(index) {
      this.siteNameList.splice(index, 1);
    },
    /** 楼栋变化函数 */
    handleBanChange(val) {
      // 获取当前楼栋下的楼层
      console.log(val)
      this.getFloorList(this.form.projectId, val);
    },
    /** 查询所有项目列表用于筛选 */
    getAllProjects() {
      getAllProjectsApi().then((res) => {
        this.queryProjectList = res.code === 200 ? res.data : [];
      });
    },
    /** 查询所有楼栋列表用于筛选 */
    getAllBans() {
      getAllBansApi().then((res) => {
        this.queryBanList = res.code === 200 ? res.data : [];
      });
    },
    handleSuccess(response, file, fileList) {
      console.log(file);
      this.form.imgs.push({ name: file.name, url: response.data });
    },
    handleRemove(file) {
      console.log(file);
      this.form.imgs = this.form.imgs.filter((item) => item.url !== file.url);
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog-content {
  width: 100%;
}

.project_content {
  display: flex;
  align-items: center;
  position: relative;
  width: 217px;

  .project-select-button {
    position: absolute;
    right: 10px;
  }
}

.station-content {
  width: 60%;
  display: flex;
  flex-wrap: wrap;
  align-items: center;

  .station-item {
    display: flex;
    width: 20%;
    align-items: center;
    margin-right: 10px;

    .close-class {
      position: relative;
      right: 8px;
      bottom: 16px;
    }
  }
}

.disabled .el-upload--picture-card {
  display: none;
}
</style>
